package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("DetectmethodRestController")
public class DetectmethodRestController extends CmiEmaController {

	/**
	 * Create a new Detectmethod entity
	 * 
	 */
	@RequestMapping(value = "/newDetectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object newDetectmethod(@RequestBody Detectmethod detectmethod) {
		detectmethodService.saveDetectmethod(detectmethod);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectmethodDAO.findDetectmethodByPrimaryKey(detectmethod.getId()), 2));
	}

	@RequestMapping(value = "/restNewDetectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewDetectmethod(@RequestBody String detectmethodJson) {
		Detectmethod detectmethod = new Gson().fromJson(detectmethodJson, Detectmethod.class);
		appendReferences(detectmethod);
		detectmethodService.saveDetectmethod(detectmethod);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectmethodDAO.findDetectmethodByPrimaryKey(detectmethod.getId()), 2));
	}

	@RequestMapping(value = "/saveDetectmethod", method = RequestMethod.PUT)
	@ResponseBody
	public Detectmethod saveDetectmethod(@RequestBody Detectmethod detectmethod) {
		detectmethodService.saveDetectmethod(detectmethod);
		return detectmethodDAO.findDetectmethodByPrimaryKey(detectmethod.getId());
	}

	@RequestMapping(value = "/restSaveDetectmethod", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveDetectmethod(@RequestBody String detectmethodJson) {
		Detectmethod detectmethod = new Gson().fromJson(detectmethodJson, Detectmethod.class);
		appendReferences(detectmethod);
		CmiPsonService cmiPsonService = new CmiPsonService();
		detectmethodService.saveDetectmethod(detectmethod);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectmethodDAO.findDetectmethodByPrimaryKey(detectmethod.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteDetectmethod/{detectmethodId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteDetectmethod(@PathVariable Integer detectmethodId) {
		Detectmethod detectmethod = detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId);
		detectmethodService.deleteDetectmethod(detectmethod);
	}

	@RequestMapping(value = "/restConfirmDeleteDetectmethods")
	@ResponseBody
	public Object restConfirmDeleteDetectmethods(@RequestBody Set<Integer> deleteDetectmethodsIds) {
		Set<Detectmethod> deleteDetectmethods = detectmethodDAO.findDetectmethodsByIds(deleteDetectmethodsIds);
		Set<Detectmethod> referencedDetectmethods = detectmethodService.loadReferenceDetectmethods(deleteDetectmethods);
		deleteDetectmethods.removeAll(referencedDetectmethods);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedDetectmethods);
		jsonObject.put("deleteEntitys", deleteDetectmethods);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteDetectmethods")
	@ResponseBody
	public Object restDeleteDetectmethods(@RequestBody Set<Detectmethod> deleteDetectmethods) {
		Iterator<Detectmethod> iterator = deleteDetectmethods.iterator();
		while (iterator.hasNext()) {
			Detectmethod currentDetectmethod = iterator.next();
			detectmethodService.deleteDetectmethod(currentDetectmethod);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listDetectmethods");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadDetectmethod/{detectmethodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectmethod(@PathVariable Integer detectmethodId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadDetectmethodDetectdetails/{detectmethodId}/detectdetails/{relateddetectdetailId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectmethodDetectdetails(@PathVariable Integer detectmethodId,
			@PathVariable Integer relateddetectdetailId, @RequestBody CmiPagination cmiPagination) {
		Detectdetail detectdetail = detectdetailDAO.findDetectdetailByPrimaryKey(relateddetectdetailId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectdetail, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectmethodFeatures/{detectmethodId}/features/{relatedfeatureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectmethodFeatures(@PathVariable Integer detectmethodId,
			@PathVariable Integer relatedfeatureId, @RequestBody CmiPagination cmiPagination) {
		Feature feature = featureDAO.findFeatureByPrimaryKey(relatedfeatureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(feature, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectmethodFoodbatchs/{detectmethodId}/foodbatchs/{relatedfoodbatchId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectmethodFoodbatchs(@PathVariable Integer detectmethodId,
			@PathVariable Integer relatedfoodbatchId, @RequestBody CmiPagination cmiPagination) {
		Foodbatch foodbatch = foodbatchDAO.findFoodbatchByPrimaryKey(relatedfoodbatchId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatch, 2, cmiPagination));
	}

	public void appendReferences(Detectmethod detectmethod) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectdetail> detectdetailsForDetectmethod = new HashSet<>();
		for (Detectdetail detectdetail_Detectmethod : detectmethod.getDetectdetailsForDetectmethod()) {
			detectdetailsForDetectmethod
					.add(detectdetailService.findDetectdetailByPrimaryKey(detectdetail_Detectmethod.getId()));
		}
		detectmethod.setDetectdetailsForDetectmethod(detectdetailsForDetectmethod);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Feature> featuresForDetectmethod = new HashSet<>();
		for (Feature feature_Detectmethod : detectmethod.getFeaturesForDetectmethod()) {
			featuresForDetectmethod.add(featureService.findFeatureByPrimaryKey(feature_Detectmethod.getId()));
		}
		detectmethod.setFeaturesForDetectmethod(featuresForDetectmethod);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatch> foodbatchsForDetectmethod = new HashSet<>();
		for (Foodbatch foodbatch_Detectmethod : detectmethod.getFoodbatchsForDetectmethod()) {
			foodbatchsForDetectmethod.add(foodbatchService.findFoodbatchByPrimaryKey(foodbatch_Detectmethod.getId()));
		}
		detectmethod.setFoodbatchsForDetectmethod(foodbatchsForDetectmethod);
	}

	@RequestMapping(value = "/restGetDetectmethodDetectdetails/{detectmethodId}/detectdetails", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectmethodDetectdetails(@PathVariable Integer detectmethodId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId).getDetectdetailsForDetectmethod(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectmethodFeatures/{detectmethodId}/features", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectmethodFeatures(@PathVariable Integer detectmethodId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId).getFeaturesForDetectmethod(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectmethodFoodbatchs/{detectmethodId}/foodbatchs", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectmethodFoodbatchs(@PathVariable Integer detectmethodId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId).getFoodbatchsForDetectmethod(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restListDetectmethods", method = RequestMethod.GET)
	@ResponseBody
	public Object restListDetectmethods() {
		return JSONObject.parse(cmiPsonService.toJsonString(detectmethodService.loadDetectmethods(), 2));
	}

	@RequestMapping(value = "/restListDetectmethodsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListDetectmethodsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = detectmethodPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Detectmethod> detectmethods = detectmethodDAO.findAllDetectmethods(startResult,
				cmiPagination.getPaginationSize());
		String detectmethodString = cmiPsonService.toPsonString(detectmethods, 2, cmiPagination);

		return JSONObject.parse(detectmethodString);
	}

	@RequestMapping("/detectmethodSelectBox")
	@ResponseBody
	public JSONObject detectmethodSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailService.loadDetectdetailsByIdSet(searchValue);
				break;
			case "Feature":
				entitySet = featureService.loadFeaturesByIdSet(searchValue);
				break;
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findAllDetectdetails((pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetails();
				break;
			case "Feature":
				entitySet = featureDAO.findAllFeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = featureService.countFeatures();
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Detectdetail":
				entitySet = detectdetailDAO.findDetectdetailByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetailsByName(queryword);
				break;
			case "Feature":
				entitySet = featureDAO.findFeatureByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = featureService.countFeaturesByName(queryword);
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
